package com.im.partchat.topic;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import com.im.partchat.App;
import com.im.partchat.R;
import com.im.partchat.adapter.TopicAdapter;
import com.im.partchat.topic.bean.AvatarBean;
import com.im.partchat.topic.bean.CommentBean;
import com.im.partchat.topic.bean.PraiseResponse;
import com.im.partchat.topic.bean.StringResponse;
import com.im.partchat.topic.bean.TopicBean;
import com.im.partchat.topic.bean.TopicListResponse;
import com.im.partchat.topic.manager.HomeManager;
import com.im.partchat.topic.tools.HttpUtil;
import com.im.partchat.topic.tools.JsonParser;
import com.im.partchat.topic.widget.PagedListView;
import com.im.partchat.topic.widget.PraiseTextView;
import com.im.partchat.topic.widget.SpannableTextView;
import com.im.partchat.utils.ToastUtils;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;


//所有 带有动态列表 的activity 都继承于此类
public abstract class BaseTopicFragment extends BaseFragment implements
		HomeManager.TopicPraiseCountChangeListener {
	protected PagedListView listView;
	protected App app;
	private final static int TOPIC_DELECT = 0x27;
	private int pageNumber = 1;
	protected List<TopicBean> list;
	protected TopicAdapter adapter;

	private MyHandler handler = new MyHandler(this);
	private static class MyHandler extends Handler {
		
		private WeakReference<BaseFragment> reference;
		
	    public MyHandler(BaseFragment context) {
	    	reference = new WeakReference<>(context);
	    }
	    
	    @Override
		public void handleMessage(Message msg) {
	    	final BaseTopicFragment activity = (BaseTopicFragment) reference.get();
			if(activity == null){
				return;
			}
			activity.progress.dismiss();
			activity.onNetWorkFinish(msg);
			switch (msg.what) {
			case NETWORK_SUCCESS_DATA_RIGHT: // 下拉刷新网络返回成功
				TopicListResponse response = (TopicListResponse) msg.obj;
				if (response.isSuccess()) {
					activity.list = response.getData().getItems();
					activity.listView.onFinishLoading(response.getData().hasMore());
					activity.adapter = new TopicAdapter(activity.getActivity(), activity.list);
					activity.adapter.setOnTopicBeanDeleteListener(new TopicAdapter.TopicBeanDeleteListener() {
						
						@Override
						public void onTopicBeanDeleteClick(TopicBean topicBean) {
							activity.progress.show();
							activity.deleteTopic(topicBean.getTopicId(), App.getUserBean().getId());
						}
					});
					activity.listView.setAdapter(activity.adapter);
					activity.pageNumber = 2;
					activity.onRefreshNetWorkSuccess(activity.list);
				} else {
					activity.listView.onFinishLoading(false);
					ToastUtils.showShort(response.getMessage());
				}
				break;
			case NETWORK_SUCCESS_PAGER_RIGHT: // 翻页网络返回成功
				TopicListResponse pageResponse = (TopicListResponse) msg.obj;
				if (pageResponse.isSuccess()) {
					List<TopicBean> tempList = pageResponse.getData().getItems();
					activity.list.addAll(tempList);
					activity.adapter.notifyDataSetChanged();
					//如果子类是hisRootActivity，不走下拉刷新
					if(activity.adapter.getOnTopicBeanDeleteListener() == null){
						activity.adapter.setOnTopicBeanDeleteListener(new TopicAdapter.TopicBeanDeleteListener() {
							
							@Override
							public void onTopicBeanDeleteClick(TopicBean topicBean) {
								// TODO Auto-generated method stub
								activity.progress.show();
								activity.deleteTopic(topicBean.getTopicId(), App.getUserBean().getId());
							}
						});
					}

					activity.listView.onFinishLoading(pageResponse.getData().hasMore());
					activity.pageNumber++;
					activity.onPagedNetWorkSuccess(activity.list);
				} else {
					activity.listView.onFinishLoading(false);
					ToastUtils.showShort(pageResponse.getMessage());
				}
				break;
			case TOPIC_DELECT: 	//删除某条动态 接口返回
				StringResponse topicResponse = (StringResponse) msg.obj;
				if (topicResponse.isSuccess() && activity.list!=null) {
					for (TopicBean dynamicBean : activity.list) {
						if (topicResponse.getTag().equals(dynamicBean.getTopicId())) {							
							activity.list.remove(dynamicBean);
							activity.adapter.notifyDataSetChanged();
							
							break;
						}
					}
				} else {
					ToastUtils.showShort(topicResponse.getMessage());
				}
				break;
			default:
				ToastUtils.showShort("无法连接到网络\n请稍后再试");
				activity.listView.onFinishLoading(false);
				break;
			}
		}
	};

	/**
	 * 网络访问成功
	 */
	public abstract void onNetWorkFinish(Message msg);
	
	
	/**
	 * 下拉刷新 且 网络访问成功
	 */
	public abstract void onRefreshNetWorkSuccess(List<TopicBean> list);
	
	/**
	 * 翻页 且 网络访问成功
	 */
	public void onPagedNetWorkSuccess(List<TopicBean> list){
		
	}

	/**
	 * 如果重写并返回id，表示查询某人的发布过的动态列表
	 */
	public String getTargetMemberId(){
		return "0";
	}
	
	protected void initListener() {
		// TODO Auto-generated method stub
		listView.setOnLoadMoreListener(new PagedListView.OnLoadMoreListener() {

			@Override
			public void onLoadMoreItems() {
				// TODO Auto-generated method stub
				new Thread(pageRun).start();
			}
		});
	}

	protected void initView(View view) {
		// TODO Auto-generated method stub

		app = App.getApplication();
		App.getHomeManager()
				.addOnTopicPraiseCountChangeListener(this);
	}

	protected Runnable run = new Runnable() {

		@SuppressWarnings("unchecked")
		public void run() {
			// TODO Auto-generated method stub
			TopicListResponse response = null;
			try {
				HashMap<String, String> data = new HashMap<String, String>();
				data.put("userid", App.getUserBean().getId());
				data.put("page", "1");
				data.put("memberid", "" + getTargetMemberId());
				data.putAll(getRequireHashMap());
				response = JsonParser.getTopicListResponse(HttpUtil
						.getMsg(HttpUtil.IP + getApi()+"?"+ HttpUtil.getData(data)));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (response != null) {
				handler.sendMessage(handler.obtainMessage(NETWORK_SUCCESS_DATA_RIGHT, response));
			} else {
				handler.sendEmptyMessage(NETWORK_FAIL);
			}
		}
	};

	protected Runnable pageRun = new Runnable() {

		@SuppressWarnings("unchecked")
		public void run() {
			// TODO Auto-generated method stub
			TopicListResponse response = null;
			try {
				HashMap<String, String> data = new HashMap<String, String>();
				data.put("userid", App.getUserBean().getId());
				data.put("page", "" + pageNumber);
				data.put("memberid", "" + getTargetMemberId());
				data.putAll(getRequireHashMap());
				response = JsonParser.getTopicListResponse(HttpUtil
						.getMsg(HttpUtil.IP + getApi()+"?"
								+ HttpUtil.getData(data)));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (response != null) {
				handler.sendMessage(handler.obtainMessage(
						NETWORK_SUCCESS_PAGER_RIGHT, response));
			} else {
				handler.sendEmptyMessage(NETWORK_FAIL);
			}
		}
	};

	/**
	 * 表示调用的接口是getlist（默认）
	 * 子类可以修改，比如返回getpraiselist 表示查询我赞的动态
	 */
	protected String getApi(){
		return "topic/getlist";
	}
	
	/**
	 * 子类可以重写此类来添加请求网络时候的自定义参数
	 */
	protected HashMap<String,String> getRequireHashMap(){
		return new HashMap<String, String>();
	}
	
	/**
	 * 某条动态的点赞状态改变
	 */
	@Override
	public void onTopicPraiseCountChanged(PraiseResponse interestResponse) {
		// TODO Auto-generated method stub
		if (list == null) {
			return;
		}
		if (!interestResponse.isSuccess()) {
			ToastUtils.showShort(interestResponse.getMessage());
		}
		for (int i = 0; i < list.size(); i++) {
			TopicBean bean = list.get(i);
			if (bean.getTopicId().equals(interestResponse.getTopicid())) {
				bean.setPraiseCount(interestResponse.getPraiseCnt());
				bean.setPraised(interestResponse.isStillPraise());
				//先判断 之前的点赞人列表中是否有我 contains
				boolean contains = false;
				for (CommentBean praiseMember : bean.getPraiseMembers()) {
					if (praiseMember.getMemberId().equals(App.getUserBean().getId())) {
						bean.getPraiseMembers().remove(praiseMember);
						contains = true;
						break;
					}
				}
				if (!contains) {
					CommentBean newBean = new CommentBean();
					newBean.setMemberId(App.getUserBean().getId());
                    AvatarBean avatarBean = new AvatarBean();
                    avatarBean.setSmall(App.getUserBean().getHeadUrl());
                    avatarBean.setOriginal(App.getUserBean().getHeadUrl());
					newBean.setMemberAvatar(avatarBean);
					newBean.setMemberName(App.getUserBean().getName());
					newBean.setContent("");
					bean.getPraiseMembers().add(newBean);
				}

				// 刷新界面（只刷新改变的那一个item就行）
				int firstVisiblePosition = listView.getFirstVisiblePosition()
						- listView.getHeaderViewsCount();
				int lastVisiblePosition = listView.getLastVisiblePosition();
				if (i >= firstVisiblePosition && i <= lastVisiblePosition) {
					View view = listView.getChildAt(i - firstVisiblePosition);
					if (view != null) {
						PraiseTextView tv = (PraiseTextView) view
								.findViewById(R.id.zan_count_btn);
						SpannableTextView bottom_textview = (SpannableTextView) view
								.findViewById(R.id.bottom_textview);
						TextView praise_count_textview = (TextView) view
								.findViewById(R.id.praise_count_textview);
						View bottom_praise_ll = view
								.findViewById(R.id.bottom_praise_ll);

						tv.setPraiseState(getActivity(), bean);
						bottom_praise_ll.setVisibility(bean.getPraiseMembers()
								.isEmpty() ? View.GONE : View.VISIBLE);
						praise_count_textview.setText(bean.getPraiseCount() + "人点赞");
						bottom_textview.setPraiseText(bean.getPraiseMembers(),
								new SpannableTextView.MemberClickListener() {

									@Override
									public void onMemberClick(
											CommentBean commentBean) {
										// TODO Auto-generated method stub
									}
								});
					}
				}
				break;
			}
		}
	}


	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		app.getHomeManager().removeOnTopicPraiseCountChangeListener(this);
		super.onDestroy();
	}

	//如果我在动态评论界面里发表了评论。刷新一下这条动态的评论数量
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (resultCode) {
		case TopicDetailActivity.COMMENT_COUNT_CHANGE:
			int topicId = data.getIntExtra("topicId", 0);
			int commentCnt = data.getIntExtra("commentCnt", -1);
			if (commentCnt != -1) {
				for (TopicBean bean : list) {
					if (bean.getTopicId().equals(topicId)) {
						bean.setCommentCount(commentCnt);
						adapter.notifyDataSetChanged();
						break;
					}
				}
			}
			break;
		default:
			break;
		}
	}

	//刷新
	protected void refresh() {
		new Thread(run).start();
	}

	//删除某条动态
	private void deleteTopic(String topicID, String uid) {
		new Thread(new DeleteTopicRun(topicID, uid)).start();
	}

	private class DeleteTopicRun implements Runnable {
		private String topicID;
		private String uid;

		public DeleteTopicRun(String topicID, String uid) {
			this.topicID = topicID;
			this.uid = uid;
		}

		@SuppressWarnings("unchecked")
		public void run() {
			// TODO Auto-generated method stub
			StringResponse response = null;
			try {
				HashMap<String, String> data = new HashMap<String, String>();
				data.put("userid", uid);
				data.put("topicid", topicID);
				response = JsonParser.getStringResponse(HttpUtil.postMsg(
						HttpUtil.getData(data), HttpUtil.IP + "topic/delete"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			if (response == null) {
				response = new StringResponse();
				response.setMessage("网络访问失败");
			}
			response.setTag(topicID);
			handler.sendMessage(handler.obtainMessage(TOPIC_DELECT, response));
		}
	}

//	public void hideKeyboard(View v) {
//		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
//				.hideSoftInputFromWindow(v.getWindowToken(),
//						InputMethodManager.HIDE_NOT_ALWAYS);
//	}
//
//	public void hideKeyboard() {
//		hideKeyboard(getWindow().getDecorView());
//	}
//
//	public void showKeyboard(EditText et) {
//		((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
//				.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
//	}
}
